package com.zt.questionnaire.common.utils;

import javax.servlet.http.HttpServletRequest;

public class ServletUtils {
    //private static Pattern regex = Pattern.compile("^((192\\.168|172\\.([1][6-9]|[2]\\d|3[01]))(\\.([2][0-4]\\d|[2][5][0-5]|[01]?\\d?\\d)){2}|10(\\.([2][0-4]\\d|[2][5][0-5]|[01]?\\d?\\d)){3})$");

    public static String realIp(HttpServletRequest request) {

        String x_forwarded = request.getHeader("X-Forwarded-For");
        String x_real_ip = request.getHeader("X-Real-IP");

        if (x_forwarded != null && !x_forwarded.equals("")) {
            String[] arr = x_forwarded.split(",");
            if (arr.length == 0) {
                if (x_real_ip == null || x_real_ip.equals("")) {
                    return request.getRemoteAddr();
                }
                return x_real_ip;
            } else {
                return arr[0];
            }
        } else if (x_real_ip != null && !x_real_ip.equals("")) {  //如果x-forwarded-for为空的情况下,我们则用x_real_ip
            return x_real_ip;
        } else {
            return request.getRemoteAddr();
        }
    }

    public static boolean isLan(HttpServletRequest request) {
        String ip = realIp(request);
        return RegExpUtils.isLanIp(ip);
    }

}
